package com.test.demo.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.test.demo.entity.e.DataSourceProperties;
import com.test.demo.service.DataSourceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 数据源初始化器
 */
@Component
public class DataSourceInitializer implements ApplicationRunner {
    
    private static final Logger logger = LoggerFactory.getLogger(DataSourceInitializer.class);
    
    @Autowired
    private DataSourceService dataSourceService;
    
    @Autowired
    private DynamicDataSource dynamicDataSource;
    
    @Override
    public void run(ApplicationArguments args) {
        logger.info("开始初始化其他数据源...");
        try {
            List<DataSourceProperties> dataSourceList = dataSourceService.getAllEnabledDataSources();
            for (DataSourceProperties properties : dataSourceList) {
                DruidDataSource dataSource = new DruidDataSource();
                dataSource.setDriverClassName(properties.getDriverClassName());
                dataSource.setUrl(properties.getUrl());
                dataSource.setUsername(properties.getUsername());
                dataSource.setPassword(properties.getPassword());
                // 设置其他连接池属性
                dataSource.setInitialSize(5);
                dataSource.setMinIdle(10);
                dataSource.setMaxActive(20);
                
                dynamicDataSource.addDataSource(properties.getDatasourceKey(), dataSource);
                logger.info("成功添加数据源: {}", properties.getDatasourceKey());
            }
        } catch (Exception e) {
            logger.error("初始化数据源失败", e);
        }
    }
} 